/**
 * Project Name:CourtTest元数据管理系统
 * File Name:SearchCourt.java
 * Package Name:main.java.com.search
 * Description:    TODO(用一句话描述该文件做什么)
 * Date:2016年6月15日下午4:44:11
 * Copyright (c) 2016, 中国软件与技术服务股份有限公司 版权所有.
 *
 */
package com.css.sword.knowing.search.test;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.elasticsearch.ElasticsearchException;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;

import com.css.sword.knowing.search.SearchField;
import com.css.sword.knowing.search.SearchInput;
import com.css.sword.knowing.search.SearchResult;
import com.css.sword.knowing.search.Searcher;
import com.css.sword.knowing.search.ValueRange;
import com.css.sword.knowing.search.aggregation.AggResult;
import com.css.sword.knowing.search.aggregation.BucketResult;
import com.css.sword.knowing.search.aggregation.MetricsResult;
import com.css.sword.knowing.search.comm.SearchConst;
import com.css.sword.knowing.search.exception.ArgException;

/**
 * ClassName: SearchCourt <br/>
 * Function: TODO ADD FUNCTION. <br/>
 * date: 2016年6月15日 下午4:44:11 <br/>
 *
 * @author hxCai
 * @version
 * @since JDK 1.7
 */
public class SearchCourt {

    private String indexName = "";
    private String[] typeName = {};

    private String[] keywords = {};
    private String caseType = "";
    private String description = "";
    private String spcx = "";
    private String startDate = "";
    private String endDate = "";
    private int pagesize = 10;
    private int pageno = 1;

    public String getIndexName() {
        return indexName;
    }

    public void setIndexName(String indexName) {
        this.indexName = indexName;
    }

    public String[] getTypeName() {
        return typeName;
    }

    public void setTypeName(String[] typeName) {
        this.typeName = typeName;
    }

    public String[] getKeywords() {
        return keywords;
    }

    public void setKeywords(String[] keywords) {
        this.keywords = keywords;
    }

    public String getSpcx() {
        return spcx;
    }

    public void setSpcx(String spcx) {
        this.spcx = spcx;
    }

    public String getCaseType() {
        return caseType;
    }

    public void setCaseType(String caseType) {
        this.caseType = caseType;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public String getStartDate() {
        return startDate;
    }

    public void setStartDate(String startDate) {
        this.startDate = startDate;
    }

    public String getEndDate() {
        return endDate;
    }

    public void setEndDate(String endDate) {
        this.endDate = endDate;
    }

    public int getPagesize() {
        return pagesize;
    }

    public void setPagesize(int pagesize) {
        this.pagesize = pagesize;
    }

    public int getPageno() {
        return pageno;
    }

    public void setPageno(int pageno) {
        this.pageno = pageno;
    }

    public String indexSearch(String name) throws IOException, ElasticsearchException, ArgException {
        String jsonString = "";

        SearchInput si = new SearchInput();
        si.setIndexName(indexName);
        si.setTypeNames(typeName);

        ArrayList<SearchField> where = new ArrayList<SearchField>();

        if (caseType.length() > 0) {
            SearchField sf = new SearchField();
            sf.setField("anjianleixing");
            sf.setOperator(SearchConst.SEARCH_OPERATOR_MUST);
            sf.setSearchValue(caseType);

            sf.setBoost(0);

            where.add(sf);
        }

        if (description.length() > 0) {
            SearchField f = new SearchField();
            f.setField("doccontent");
            f.setOperator(SearchConst.SEARCH_OPERATOR_SHOULD);
            f.setSearchValue(description);

            f.setBoost(1);

            where.add(f);
        }

        if (keywords.length > 0) {
            SearchField f = new SearchField();
            f.setField("keywords");
            f.setOperator(SearchConst.SEARCH_OPERATOR_SHOULD);
            f.setSearchValue(keywords);

            f.setBoost(1);

            where.add(f);
        }

        if (startDate.length() > 0) {
            if (endDate.length() < 0) {
                SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");// 设置日期格式
                endDate = df.format(new Date());
            }

            SearchField f = new SearchField();
            f.setField("caipanriqi");
            // f.setOperator(SearchConst.SEARCH_OPERATOR_MUST);
            f.setMethod(SearchConst.SEARCH_METHOD_RANGE);

            ValueRange vr1 = new ValueRange();
            // vr1.setComparison1(SearchConst.COMPARISON_OP_GTE);
            // vr1.setValue1(startDate);
            vr1.setComparison2(SearchConst.COMPARISON_OP_LTE);
            vr1.setValue2(endDate);
            f.setValueRanges(vr1);

            f.setBoost(0);

            where.add(f);
        }

        si.setSearchFields(where);
        si.setReturnFields(new String[] { "anjianmingcheng", "caipanriqi" });

        si.setSystemID("public");
        si.setFrom((pageno - 1) * pagesize);
        si.setSize(pagesize);

        List<SearchInput> sis = new ArrayList<SearchInput>();
        sis.add(si);

        List<SearchResult> rss = Searcher.multiIndexSearch(sis);

        jsonString = rss2Json(rss);

        return jsonString;
    }

    public String rss2Json(List<SearchResult> rss) throws IOException {
        XContentBuilder jsonBuilder = XContentFactory.jsonBuilder();

        for (SearchResult rs : rss) {
            long count = rs.getTotalNum();
            long pagenum = (long) Math.ceil((double) count / pagesize);

            jsonBuilder.startObject();

            jsonBuilder.field("count", rs.getTotalNum());
            jsonBuilder.field("total", rs.getTotalNum());
            jsonBuilder.field("pagenum", pagenum);

            jsonBuilder.startArray("docs");
            List<Map> data = rs.getData();
            String key = null;
            Object value = null;
            for (Map<String, String> fields : data) {
                jsonBuilder.startObject();
                Iterator<String> it = fields.keySet().iterator();
                while (it.hasNext()) {
                    key = it.next();
                    value = fields.get(key);

                    if ("_id".equalsIgnoreCase(key))
                        continue;

                    if ("doccontent".equalsIgnoreCase(key)) {
                        key = "summary";
//                        value = CssKM.km_summary("", "", value.toString(), "", "", 300, false);
                    }
                    jsonBuilder.field(key, value);
                }
                jsonBuilder.endObject();
            }
            jsonBuilder.endArray();

            break;
        }

        jsonBuilder.endObject();

        String jsonString = jsonBuilder.string();

        return jsonString;
    }

    public String getSearch(String name) throws IOException, ElasticsearchException, ArgException {

        XContentBuilder jsonBuilder = XContentFactory.jsonBuilder();

        return indexSearch(name);
    }

    private String getString1(String context, String tag, int position) {
        String str = context.replaceAll("[ |　]", "");
        String ret = "";

        int pos = str.indexOf(tag, position);
        while (pos > 0) {
            int npos = str.indexOf("\n", pos + 1);

            if (npos > pos) {
                String s = str.substring(pos, npos);

                s = s.replace(tag, "");
                if (s.length() < 5) {
                    if (ret.length() > 0)
                        ret += ",";

                    ret += s;
                }
            }

            pos = str.indexOf(tag, pos + tag.length());
        }
        return ret;
    }

    public String getDetail(String index, String type, String docID)
            throws IOException, ElasticsearchException, ArgException {

        XContentBuilder jsonBuilder = XContentFactory.jsonBuilder();

        SearchInput si = new SearchInput();
        si.setIndexName(index);
        si.setTypeNames(new String[] { type });

        ArrayList<SearchField> where = new ArrayList<SearchField>();

        if (docID.length() > 0) {
            SearchField sf = new SearchField();
            sf.setField("docid");
            sf.setOperator(SearchConst.SEARCH_OPERATOR_MUST);
            sf.setSearchValue(docID);
            where.add(sf);
        }

        si.setSearchFields(where);
        si.setReturnFields(new String[] { "docid", "anjianmingcheng", "anjianleixing", "reason", "anhao",
                "shenpanchengxu", "caipanyaozhi", "appellor", "legalbase", "fayuanmingcheng", "doccontent", "context",
                "caipanriqi" });

        si.setSystemID("public");
        si.setFrom(0);
        si.setSize(1);

        List<SearchInput> sis = new ArrayList<SearchInput>();
        sis.add(si);

        List<SearchResult> rss = Searcher.multiIndexSearch(sis);

        for (SearchResult rs : rss) {
            jsonBuilder.startObject();

            List<Map> data = rs.getData();
            String key = null;
            Object value = null;
            for (Map<String, String> fields : data) {
                jsonBuilder.startObject("doc");
                Iterator<String> it = fields.keySet().iterator();
                while (it.hasNext()) {
                    key = it.next();
                    value = fields.get(key);

                    if ("_id".equalsIgnoreCase(key) || "_score".equalsIgnoreCase(key))
                        continue;

                    if (key.equals("appellor")) {
                        String str = value.toString();
                        String[] arr = str.split(",");

                        if (arr.length > 0) {
                            jsonBuilder.field("beigao", arr[arr.length - 1]);

                            String s = str.substring(0, str.length() - arr[arr.length - 1].length() - 1);

                            jsonBuilder.field("yuangao", s);
                        } else {
                            jsonBuilder.field("yuangao", str);
                        }
                        continue;
                    }
                    if (key.equals("context")) {
                        String str = value.toString();

                        String spz = getString1(str, "审判长", 0);
                        if (spz.length() > 0) {
                            jsonBuilder.field("shenpanzhang", spz);
                        }

                        String spy = getString1(str, "审判员", 0);
                        if (spy.length() > 0) {
                            jsonBuilder.field("shenpanyuan", spy);
                        }

                        String sjy = getString1(str, "书记员", 0);
                        if (sjy.length() > 0) {
                            jsonBuilder.field("shujiyuan", sjy);
                        }
                    }

                    jsonBuilder.field(key, value);
                }
                jsonBuilder.endObject();

                break;
            }

            break;
        }

        jsonBuilder.endObject();

        String jsonString = jsonBuilder.string();

        return jsonString;
    }

    public static void main(String[] args) throws IOException, ElasticsearchException, ArgException {

        // String[] ret = getSuggest("news", "新", 10, false);
        // System.out.println(Arrays.asList(ret));
        //

        SearchCourt s = new SearchCourt();

        s.setIndexName("court");
        s.setTypeName(new String[] { "court_all" });
        s.setKeywords(new String[] { "黑龙江省", "宁安市", "人民法院", "2014", "172号", "原告", "被告", "原告", "被告", "保证", "合同纠纷", "一案",
                "本院", "2014年", "6月", "18日", "受理", "依法", "适用", "简易程序", "2014年", "7月", "11日", "公开", "开庭", "进行了" });
        s.setCaseType("民事案件");
        s.setStartDate("2016-01-01");
        s.setEndDate("2016-06-06");
        s.setDescription(
                "2014年3月24日，陶会波向原告韩世海借款19万元，约定月利息3分，并向原告出具借款19万元的一份借据，双方约定月利息3分，用宁安镇镜泊新鑫家园3号楼1单元301室楼房做担保。陶会波在借款人处签字，被告陶明忠在担保人处签字。被告担保借款后，每月给付原告利息至2014年3月24日。自2014年3月25日至2014年7月25日，中国人民银行同期同类贷款基准利率年利率为5.6%，核月利息0.00466元。 据以上事实，本院认为，依法成立的合同，对当事人具有法律约束力。当事人应当按照约定全面履行自己的义务。原告韩世海作为出借人已履行了出借义务，被告陶明忠作为担保人应当按照约定的期限保证返还借款。本案中，陶会波向原告韩世海借款，被告陶明忠在担保人处签字确认，原告与被告形成了担保关系且合法有效。因双方对保证方式没有约定，应认定为承担连带责任保证；连带责任保证的债务人在主合同规定的债务履行期届满没有履行债务的，债权人可以要求债务人履行债务，也可以要求保证人在其保证范围内承担保证责任。因此，原告向被告提起诉讼，要求担保人陶明忠承担保证责任符合法律规定。 原告与被告约定借款利息为月利息3分，其约定利息标准超出法律规定，其超出部分不予支持。根据中国人民银行同期同类贷款基准利率年利率为5.6%的4倍即月利息1.87分计算自2014年3月25日至2014年7月25日止借款本金19万元利息为14212元。 原告要求被告给付自2014年7月26日起至借款还清止按中国人民银行同类贷款利率计算利息的诉讼请求合理合法，本院应支持原告利息至本判决确定的最后履行之日止");

        s.setPagesize(10);
        s.setPageno(1);

        String ret = s.getSearch("court_all");

        System.out.println("++++++++++++++++++json++++++++++++++++++++");
        System.out.println(ret);

        // String detail = s.getDetail("court", "court_all",
        // "eb05fd04-224e-4d01-a595-f473f146219c");
        // System.out.println("++++++++++++++++++detail++++++++++++++++++++");
        // System.out.println(detail);

        // s.agg();

        // Searcher.terms("artistnews", "news");
        // Searcher.b();
    }
}
